import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class TimezoneInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(map((data) => this.convertToChinaTime(data)));
  }

  private convertToChinaTime(data: any): any {
    if (data instanceof Date) {
      const chinaTime = new Date(
        data.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' }),
      );
      return chinaTime;
    }
    return data;
  }
}
